package com.example.emplyee;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

@Controller
public class MyController {
    List<Employee> employeesList = new ArrayList<>();

    //获取主机信息
    public String getAddress() {
        InetAddress add = null;
        try {
            add = InetAddress.getLocalHost();
            return "主机地址：" + add.getHostAddress() + "主机名：" + add.getHostName();

        } catch (UnknownHostException e) {
            e.printStackTrace();
            return "无法获取主机地址";
        }
    }

    //首页
    @RequestMapping("/")
    public String indexFile(Model model) {
        String address = getAddress();
        model.addAttribute("hostAddress", address);
        return "indexpage";
    }

    @RequestMapping("/loadmessagepage")
    public String insertPage(Model model) {
        model.addAttribute("hostAddress", getAddress());
        return "loadmessagepage";
    }

    @RequestMapping("addemployee")
    @ResponseBody
    public String addEmployee(@Valid Employee emp, BindingResult result) {
        if (result.hasErrors()) {
            for (ObjectError error : result.getAllErrors()) {
                System.out.println(error.getDefaultMessage());
            }
            return "参数为空或超出范围";
        } else {
            employeesList.add(emp);
            return "职工信息插入成功！";
        }

    }

    @RequestMapping("/selectmessagepage")
    public String select(Model model){
        model.addAttribute("hostAddress",getAddress());
        model.addAttribute("emplist",employeesList);
        return "selectmessagepage";

    }

}
